// 创建 Chart.js 的图表对象
const ctx = document.getElementById('attendance-chart').getContext('2d');
let attendanceChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['出勤', '缺勤'],
        datasets: [{
            label: '出勤和缺勤统计',
            data: [0, 0],
            backgroundColor: [
                'rgba(75, 192, 192, 0.2)',
                'rgba(255, 99, 132, 0.2)'
            ],
            borderColor: [
                'rgba(75, 192, 192, 1)',
                'rgba(255, 99, 132, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});

// 创建 WebSocket 连接
const socket = new WebSocket('ws://localhost:8080/');

// 当 WebSocket 连接打开时
socket.addEventListener('open', function (event) {
    console.log('WebSocket 连接已建立');
});

// 当接收到消息时
socket.addEventListener('message', function (event) {
    const data = event.data;
    // 解析从后端接收到的数据，假设格式是 "总出勤数: X, 总缺勤数: Y"，你可根据实际后端发送格式调整解析逻辑
    const parts = data.split(',');
    const attendance = parseInt(parts[0].split(':')[1].trim());
    const absence = parseInt(parts[1].split(':')[1].trim());
    // 更新图表数据
    attendanceChart.data.datasets[0].data = [attendance, absence];
    attendanceChart.update();
});

// 当 WebSocket 连接关闭时
socket.addEventListener('close', function (event) {
    console.log('WebSocket 连接已关闭');
});